// pages/study/index.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    currentTab: 'learning', // 当前选中的标签：learning-正在学习，finished-已学完
    learningCourses: [], // 正在学习的课程
    finishedCourses: [], // 已学完的课程
    totalStudyDays: 0, // 总学习天数
    totalStudyTime: 0, // 总学习时长(小时)
    totalCourses: 0, // 学习课程数
    calendar: [] // 学习日历数据
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.initCalendar();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.loadStudyData();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    this.loadStudyData();
    setTimeout(() => {
      wx.stopPullDownRefresh();
    }, 1000);
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    return {
      title: '我的学习进度',
      path: '/pages/index/index'
    }
  },

  /**
   * 切换标签
   */
  switchTab(e) {
    const tab = e.currentTarget.dataset.tab;
    this.setData({
      currentTab: tab
    });
  },

  /**
   * 加载学习数据
   */
  loadStudyData() {
    // 检查登录状态
    const userInfo = wx.getStorageSync('userInfo');
    const token = wx.getStorageSync('token');
    
    if (!userInfo || !token) {
      this.setData({
        learningCourses: [],
        finishedCourses: [],
        totalStudyDays: 0,
        totalStudyTime: 0,
        totalCourses: 0
      });
      return;
    }
    
    // 模拟API调用
    setTimeout(() => {
      // 模拟正在学习的课程数据
      const learningCourses = [
        {
          id: '1',
          title: 'Vue.js 3.0 从入门到精通',
          coverUrl: '/assets/images/course/vue3.png',
          progress: 35,
          lastStudyTime: '2023-06-15 20:30'
        },
        {
          id: '2',
          title: 'React 18 实战教程',
          coverUrl: '/assets/images/course/react.png',
          progress: 68,
          lastStudyTime: '2023-06-18 15:45'
        }
      ];
      
      // 模拟已学完的课程数据
      const finishedCourses = [
        {
          id: '3',
          title: 'JavaScript 高级编程',
          coverUrl: '/assets/images/course/javascript.png',
          finishTime: '2023-05-20'
        },
        {
          id: '4',
          title: 'CSS 动画与特效',
          coverUrl: '/assets/images/course/css.png',
          finishTime: '2023-04-10'
        }
      ];
      
      // 更新数据
      this.setData({
        learningCourses,
        finishedCourses,
        totalStudyDays: 28,
        totalStudyTime: 45.5,
        totalCourses: learningCourses.length + finishedCourses.length
      });
    }, 500);
  },

  /**
   * 初始化学习日历
   */
  initCalendar() {
    const now = new Date();
    const year = now.getFullYear();
    const month = now.getMonth();
    const today = now.getDate();
    
    // 获取当月天数
    const daysInMonth = new Date(year, month + 1, 0).getDate();
    
    // 获取当月第一天是星期几
    const firstDayOfMonth = new Date(year, month, 1).getDay();
    
    // 生成日历数据
    const calendar = [];
    let dayCounter = 1;
    
    // 模拟学习记录
    const studyDays = [3, 5, 8, 10, 12, 15, 18, 20, 22, 25, 26];
    
    // 生成日历网格（6行7列）
    for (let week = 0; week < 5; week++) {
      const days = [];
      
      for (let day = 0; day < 7; day++) {
        if ((week === 0 && day < firstDayOfMonth) || dayCounter > daysInMonth) {
          // 填充空白
          days.push({
            day: '',
            date: null,
            hasStudy: false
          });
        } else {
          // 填充日期
          const hasStudy = studyDays.includes(dayCounter) || (dayCounter === today);
          days.push({
            day: dayCounter,
            date: `${year}-${month + 1}-${dayCounter}`,
            hasStudy
          });
          dayCounter++;
        }
      }
      
      calendar.push({
        week,
        days
      });
      
      // 如果已经填完当月所有日期，跳出循环
      if (dayCounter > daysInMonth) {
        break;
      }
    }
    
    this.setData({
      calendar
    });
  },

  /**
   * 继续学习
   */
  continueLearning(e) {
    const courseId = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/course/video?id=${courseId}`
    });
  },

  /**
   * 再学一遍
   */
  reviewCourse(e) {
    const courseId = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/course/video?id=${courseId}&review=1`
    });
  },

  /**
   * 跳转到课程详情
   */
  goCourseDetail(e) {
    const courseId = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/course/detail?id=${courseId}`
    });
  },

  /**
   * 跳转到课程列表
   */
  goCourseList() {
    wx.switchTab({
      url: '/pages/course/list'
    });
  }
})